package Tydzien6;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.logging.*;

import Tydzien4.Biblioteka;

public class KsiazkaDao implements Dao<Biblioteka> {
	
	File file;
	
	public KsiazkaDao(String filename)
	{
		try
		{
			this.file = new File(filename);
			file.createNewFile();
		}
		catch (NullPointerException ne) {
			throw new NullException(ne.getMessage(), ne.getCause());
		}
		catch(IOException io)
		{
			Logger.getLogger("ExceptionLog").log(Level.SEVERE, io.getMessage());
		}
		
	}
	
	@Override
	public void add(Biblioteka collection) {
		try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))) {
			out.writeObject(collection);
		} 
		catch (IOException io) {
			Logger.getLogger("ExceptionLog").log(Level.SEVERE, io.getMessage());
		}
	}

	@Override
	public Biblioteka get() throws WrongClassException {
		try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
			return (Biblioteka) in.readObject();
		} 
		catch (FileNotFoundException io) {
			Logger.getLogger("ExceptionLog").log(Level.SEVERE, io.getMessage());
		} 
		catch (IOException io) {
			Logger.getLogger("ExceptionLog").log(Level.SEVERE, io.getMessage());
		} 
		catch (ClassNotFoundException e) {
			throw new WrongClassException(e.getMessage(), e.getCause());
		}
		return null;
	}
}
